package com.qf.cx.simplenms.subscriber.impl;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MaxSizeQueue<E> {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private final LinkedList<E> cache;
	private final int maxSize;

	public MaxSizeQueue(int maxSize) {
		this.maxSize = maxSize;
		this.cache = new LinkedList<>();
	}

	public void add(E e) {
		List<E> removed = new ArrayList<>();
		synchronized (cache) {
			while (cache.size() >= maxSize) {
				removed.add(cache.removeFirst());
			}
			cache.addLast(e);
			cache.notifyAll();
		}
		if (!removed.isEmpty()) {
			logger.warn("drop " + removed);
		}

	}

	public synchronized E take() throws InterruptedException {
		E first = null;
		synchronized (cache) {
			while (cache.isEmpty()) {
				cache.wait();
			}
			first = cache.removeFirst();
		}
		return first;
	}
}
